class Admin::UsersController < ApplicationController
  before_action :authenticate_super_admin!
  respond_to :html, :js

  def index
    @users = User.order(created_at: :desc)

    respond_to do |format|
      format.html
      format.json
    end
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
    @roles = []
  end

  def create
    @user = User.new(create_permit_params)
    if @user.save
      flash[:notice] = 'User created successfully.'
    else
      flash[:notice] = 'User created failed.'
    end
    redirect_to admin_users_path
  end

  def edit
    @user = User.find(params[:id])
    @roles = YAML::load(@user.roles)
  end

  def update
    @user = User.find(params[:id])
    if @user.update(update_permit_params)
      flash[:notice] = 'User updated successfully.'
    else
      flash[:notice] = 'User updated failed.'
    end
    redirect_to admin_users_path
  end

  def destroy

  end

  protected

  def update_permit_params
    roles = YAML::dump(params[:user][:roles].select { |role| role.size > 0 }.map { |role| role.to_sym })
    params[:user][:roles] = roles
    if params[:user][:password].size > 0
      params[:user].permit(:name, :email, :password, :roles)
    else
      params[:user].permit(:name, :email, :roles)
    end
  end

  def create_permit_params
    roles = YAML::dump(params[:user][:roles].select { |role| role.size > 0 }.map { |role| role.to_sym })
    params[:user][:roles] = roles
    params[:user].permit(:name, :email, :password, :roles)
  end
end
